# -*- coding: utf-8 -*-
from django.utils.translation import ugettext as _
from django.http import HttpResponse, HttpResponseRedirect
from django.db import models
from django.conf import settings
from django.views.decorators.cache import cache_page
from catalog.models import Organization, OrgType, Dataset, TRI_STATE, Suggestion, Topic, Format
from catalog.forms import SuggestForm
from util.breadcrumb import breadcrumb_from_objects
from util.comments_extra import post_comment
from django.contrib import comments
from django.shortcuts import render_to_response, get_object_or_404
from time import strftime
import datetime
from itertools import chain
from django.core.mail import send_mail
from util.cache import expire_page
from django.core.urlresolvers import reverse

@cache_page(60 * 60)
def catalog_open(request):
    breadcrumb = breadcrumb_from_objects([{"title": "Data", "url": "/data/"}])
    page_title = u"Open datasets"
    current = "data"
    open_formats = Format.objects.filter(is_open='Y')
    datasets = Dataset.objects.filter(license__is_free=True, formats__id__in=[f.id for f in open_formats]).distinct().order_by("-id")
    topics = Topic.objects.all().order_by("name")
    return render_to_response('catalog_open.html', locals())

@cache_page(60 * 60)
def catalog_all(request):
    breadcrumb = breadcrumb_from_objects([{"title": "Data", "url": "/data/"}])
    page_title = u"All datasets"
    current = "data"
    datasets = Dataset.objects.all()
    topics = Topic.objects.all().order_by("name")
    return render_to_response('catalog_all.html', locals())

def catalog_suggest(request):
    if request.method == 'POST': # If the form has been submitted...
        form = SuggestForm(request.POST) # A form bound to the POST data
        if form.is_valid():
            s = Suggestion()
            s.name = form.cleaned_data['name']
            s.agency = form.cleaned_data['agency']
            s.description = form.cleaned_data['description']
            s.url = form.cleaned_data['url']
            s.submitter_name = form.cleaned_data['submitter_name']
            s.submitter_email = form.cleaned_data['submitter_email']
            s.save()

            # TODO: Implement email to admin here

            # Expire cached versions of these pages
            expire_page("/")
            expire_page("/data/")
            expire_page("/data/suggest/")
            return HttpResponseRedirect(reverse('vwpage', args=('thankyou',))) # Redirect to thenak you page after POST
        else:
            pass
    else:
        form = SuggestForm()

    breadcrumb = breadcrumb_from_objects([{"title": "Data", "url": "/data/"}])
    page_title = _("Suggest dataset")
    current = "data"

    recent_suggestions = Suggestion.objects.all().order_by("-id")[:10]
    return render_to_response('catalog_suggest.html', locals())


#@cache_page(60 * 60)
def catalog_index(request):
    #List latest datasets

    recent_datasets = Dataset.objects.all().order_by("-submit_date")[:20]
    topics = Topic.objects.all().order_by("name")

    page_title = _("Public data sets")

    current = "data"
    return render_to_response('catalog_index.html', locals())



@cache_page(60 * 60)
def catalog_item(request, item_id):
    item = get_object_or_404(Dataset, pk=item_id)
    item_topics = item.topics.all()

    breadcrumb = breadcrumb_from_objects([{"title": "Data", "url": "/data/"}])

    related_items = []
    if len(item_topics) > 0:
        related_items = Dataset.objects.filter(topics__id__in=[t.id for t in item_topics]).exclude(id=item.id).distinct()[:10]

    page_title = item.name 
    current = "data"

    if request.method == "POST":
        return post_comment(request, None, item, locals(), "catalog_item.html")

    #default form
    form = comments.get_form()(item, None)

    return render_to_response('catalog_item.html', locals())


def catalog_item_rdf(request, item_id):
    dataset = get_object_or_404(Dataset, pk=item_id)
    return HttpResponse(dataset.to_rdfxml(), mimetype="application/rdf+xml; charset=utf-8") 


@cache_page(10 * 60)
def catalog_org(request, slug):
    item = get_object_or_404(Organization, slug=slug)
    datasets = item.datasets.all()

    breadcrumb = breadcrumb_from_objects([{"title": "Data", "url": "/data/"}])

    page_title = item.name 
    current = "data"
    return render_to_response('catalog_org.html', locals())


@cache_page(60 * 60)
def catalog_format(request, slug):
    item = get_object_or_404(Format, slug=slug)
    datasets = item.datasets.all().order_by("-submit_date")[:10]
    breadcrumb = breadcrumb_from_objects([{"title": "Data", "url": "/data/"}])

    page_title = u"Format: %s" % item.name 
    current = "data"
    return render_to_response('catalog_format.html', locals())


@cache_page(60 * 60)
def catalog_topic(request, slug):
    item = get_object_or_404(Topic, slug=slug)
    datasets = item.datasets.all()
    topics = []
    if not datasets:
        topics = Topic.objects.all().order_by("name")

    breadcrumb = breadcrumb_from_objects([{"title": "Data", "url": "/data/"}])

    page_title = u"Datasets tagged with '%s'" % item.name 
    current = "data"
    return render_to_response('catalog_topic.html', locals())


#@cache_page(60 * 60)
def datafeed(request):
    datasets = Dataset.objects.order_by('-submit_date')
    last_updated = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S+01:00")
    site_base_url = settings.SITE_BASE_URL
    
    if len(datasets) > 0:
        last_updated = datasets[0].submit_date.strftime("%Y-%m-%dT%H:%M:%S+01:00")
    return render_to_response('datasetfeed.html', locals(), mimetype='application/atom+xml')


def search(request):
    #Use google custom search
    page_title = u"Search result"
    return render_to_response('searchresult_google.html', locals())

